﻿using ChuanYe.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using System.Xml;
using System.Data;
using ChuanYe.DAL;
using SJPlatForm.Web.Controllers;
using Microsoft.AspNet.SignalR;
using ChuanYe.Commom;
using SJPlatForm.Web.Models;
using ChuanYe.Models.Model;
using ChuanYe.Models;

namespace SJPlatForm.Web
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        readonly FireInfoDAL dal = new FireInfoDAL();

        readonly UsersInfosDAL userDal = new UsersInfosDAL();

        XmlDocument xmlDoc = new XmlDocument();
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //火灾处置相关
            string fcdFilePath = AppDomain.CurrentDomain.BaseDirectory + "FireCountDown.xml";
            var t = Task.Factory.StartNew(() =>
            {
                FireCountDown(fcdFilePath);
            });
        }


        /// <summary>
        /// 接收请求
        /// </summary>
        protected void Application_BeginRequest()
        {


            //此出用于记录用的的登陆状态，迭代原因:Cache会被IIS回收,没有第三方缓存
            try
            {
                string id = Request.Headers.GetValues("ID")?.FirstOrDefault();
                if (id != null)
                {
                    id = HttpUtility.UrlDecode(id);
                    var loginUserCache = userDal.GetLoginUserCache(id.ToInt());
                    loginUserCache.StartTime = DateTime.Now;
                    loginUserCache.Value = 60 * 12;//单位:分钟
                    userDal.AddOrUpdateLoginUserCache(loginUserCache);
                }
            }
            catch (Exception ex)
            {
            
            }

        }

        protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null &&
                app.Context != null)
            {
                //移除接口中的 iis 信息
                app.Context.Response.Headers.Remove("Server");
            }
        }

        private void FireCountDown(string filePath)
        {
            var hub = new Lazy<IHubContext>(() => GlobalHost.ConnectionManager.GetHubContext<FireDisposalChatHub>()).Value;

            //1.火灾倒计时配置文件是否存在
            if (!File.Exists(filePath))
            {
                string[] defaultString = { "<?xml version=\"1.0\" encoding=\"utf-8\" ?>", "<Fire></Fire>" };
                File.WriteAllLines(filePath, defaultString);
            }

            while (true)
            {
                Thread.Sleep(5000);
                try
                {
                    //维护与保持 FireCountDown XML 文件
                    List<FireCountDownModel> removeList = Pickout.FireCountDownMaintain(filePath);
                    foreach (var item in removeList)
                    {
                        var mr = dal.MRListByFireIDs(new List<int>() { item.FireID }).FirstOrDefault();
                        if (mr == null)
                        {
                            continue;
                        }
                        var info = dal.FireInfoDetail(item.FireID);
                        if (info!=null && info.F_IsState != 0)
                        {
                            Pickout.RemoveCountDownElement(new FireCountDownModel()
                            {
                               FireID = info.F_FireID,
                            }, filePath);
                            continue;
                        }

                        List<M_Automatic> list = null;
                        List<int> mtypes = null;
                        string content = null;
                        int mid = 0;
                        if (item.CountDownType == (int)RecordType.首报未按时操作)
                        {
                            mtypes = new List<int>() { 17 };
                            list = dal.GetFireAutomatic(info.F_FireID, mtypes);
                            
                        }
                        if (item.CountDownType == (int)RecordType.续报未按时操作)
                        {
                            mtypes = new List<int>() { 18 };
                            list = dal.GetFireAutomatic(info.F_FireID, mtypes);
                        }
                        if (item.CountDownType == (int)RecordType.终报未按时操作)
                        {
                            mtypes = new List<int>() { 19 };
                            list = dal.GetFireAutomatic(info.F_FireID, mtypes);
                        }

                        //写入未及时首报续报终报处置记录
                        mr.MR_AddTime = DateTime.Now;
                        mr.MR_HandleTime = DateTime.Now;
                        mr.MR_Type = item.CountDownType;
                        mr.MR_UserID = 0;
                        mr.F_FireID = info.F_FireID;
                        string mrContent = string.Format(Pickout.GetFireInfoFormat(mr.MR_Type.Value), info.F_FireName);
                        mr.MR_Content = mrContent;
                        mr.MR_AddIP = CheckRequest.GetWebClientIp();
                        mr.MR_Applicant = string.Empty;
                        mr.MR_AddUser = info.F_TransUser.ToInt();
                        mr.CFA_ID = 0;
                        dal.AddRecord(mr);



                        //将已经未及时操作的消息设置成未读
                        //在完成首报 续报 终报时 会删除此消息
                        if (list !=null && list.Count >0)
                        {
                            dal.UpdateFireAutoMatic(info.F_FireID, mtypes, 1);
                            content = list.FirstOrDefault().M_Content;
                            mid = list.FirstOrDefault().M_ID;
                        }
                        content = content == null ? mrContent : content;
                       
                        //向市局发送未及时处理的首报 续报 终报
                        Pickout.SendAreaMessage(-1, info.F_FireID, mr.MR_Type.Value, mid, content);

                        //向区县发送未及时处理的首报 续报 终报
                        //Pickout.SendAreaMessage(info.F_AddressCounty.ToInt(), info.F_FireID, mr.MR_Type.Value, mid, content);
                    }
                }
                catch (Exception ex)
                {
                   
                }
            }
        }

        

    }
}
